package com.iyao_app.im.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iyao_app.R;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.UploadImage;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.RequestUrl;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.PickImageLoader;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.ToastUtil;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageCropActivity;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

public class HeadPictureActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_next)
    TextView mIvNext;
    @BindView(R.id.sdv_head)
    SimpleDraweeView mSdvHead;
    @BindView(R.id.iv_image_pai)
    ImageView mIvImagePai;
    @BindView(R.id.iv_image_tu)
    ImageView mIvImageTu;

    private String headImage = null;
    final int IMAGE_PICKER = 1;
    final static int CAMERA_RESULT = 0;//声明一个常量，代表结果码
    private User user;
    private ImagePicker imagePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_head_picture);
        ButterKnife.bind(this);
        initPicker();
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        String image = intent.getStringExtra("image");
        mSdvHead.setImageURI(image);
        user = DbUtil.getUser();
        String avatarUrl = user.avatarUrl;
        mTvTitle.setText(ResourcesUtils.getString(R.string.system_head));
        mIvNext.setText(ResourcesUtils.getString(R.string.complete));
        mSdvHead.setImageURI(avatarUrl);


    }

    @OnClick({R.id.iv_back, R.id.iv_next, R.id.iv_image_pai, R.id.iv_image_tu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_next:
                upLoadImage();
                break;
            case R.id.iv_image_pai:
                if (!(checkPermission(Manifest.permission.CAMERA))) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
                } else {
                    imagePicker.takePicture(this, ImagePicker.REQUEST_CODE_TAKE);
                }
                break;
            case R.id.iv_image_tu:
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
        }
    }
    public boolean checkPermission(@NonNull String permission) {
        return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imagePicker.takePicture(this, ImagePicker.REQUEST_CODE_TAKE);
            } else {
                ToastUtil.showToast(this, "权限被禁止，无法打开相机");
            }
        }
    }
    public static final int REQUEST_PERMISSION_CAMERA = 0x02;

    /**
     * 初始化图库
     */
    private void initPicker() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);   //显示拍照按钮
        imagePicker.setCrop(true);         //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);
        imagePicker.setSaveRectangle(true);//是否按矩形区域保存
        imagePicker.setSelectLimit(1);     //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(1000);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(1000);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);     //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);     //保存文件的高度。单位像素
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem imageItem = images.get(0);
                mSdvHead.setImageURI(ImageUtils.IMAGE_FILE + imageItem.path);
                headImage = imageItem.path;

            } else {
                //Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == RESULT_OK) {

            if (requestCode == ImagePicker.REQUEST_CODE_TAKE) {
                //发送广播通知图片增加了
                ImagePicker.galleryAddPic(this, imagePicker.getTakeImageFile());

                /**
                 * 2017-03-21 对机型做旋转处理
                 */
                String path = imagePicker.getTakeImageFile().getAbsolutePath();


                ImageItem imageItem = new ImageItem();
                imageItem.path = path;
                imagePicker.clearSelectedImages();
                imagePicker.addSelectedImageItem(0, imageItem, true);

                headImage = imagePicker.getTakeImageFile().getAbsolutePath();

                mSdvHead.setImageURI(ImageUtils.IMAGE_FILE + headImage);
                Intent intent = new Intent(HeadPictureActivity.this, ImageCropActivity.class);
                startActivityForResult(intent, ImagePicker.REQUEST_CODE_CROP);  //单选需要裁剪，进入裁剪界面
            }
        }
    }

    private void upLoadImage() {
        if (headImage != null){
        Flowable.just(headImage)
                .observeOn(Schedulers.io())
                .map(new Function<String, File>() {
                    @Override
                    public File apply(String s) throws Exception {
                        return Luban.with(HeadPictureActivity.this).load(s).get().get(0);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        int[] imageInfo = ImageUtils.getImageWidthHeight(file);
                        LogUtil.e(imageInfo[0] + "=====" + imageInfo[1]);
                        final HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("file", file);
                        NetUtils.getInstance().uploadImage(RequestUrl.UPLOAD_FILE, imageInfo[0], imageInfo[1], hashMap, new NetCallBack() {
                            @Override
                            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                                if (code == Contants.SUCCESS_CODE) {

                                    UploadImage uploadImage = model.getModel();
                                    if (uploadImage != null && !TextUtils.isEmpty(uploadImage.getFileUrl())) {
                                        complete(uploadImage.getFileUrl());
                                    }else if (uploadImage == null){
                                        finish();
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(message)) {
                                        Animation shake = AnimationUtils.loadAnimation(HeadPictureActivity.this, R.anim.shake);
                                    }
                                }
                            }

                            @Override
                            public void onFail(String message, int code) {
                                Toast.makeText(HeadPictureActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
                            }
                        }, UploadImage.class);
                    }
                });
        }else {
            finish();
        }
    }

    private void complete(final String image) {
        NetUtils.getInstance().userUpdate(user.id,image,null,null, new NetCallBack() {
            @Override
            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    user.avatarUrl=image;
                    DbUtil.updateUserInfo(user);
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.USER_INFO_REFUSH));
                    finish();

                } else {

                }
            }

            @Override
            public void onFail(String message, int code) {
                Toast.makeText(HeadPictureActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
            }
        }, null);
    }



}
